﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using PARK.CardAcct.Entitys;
using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Filter;
using PARK.Consumer.Entity;
using PARK.Consumer.Entitys.Dto.ConsumtakeEye;
using PARK.Consumer.Entitys.Dto.Wechat;
using PARK.Consumer.Interfaces;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using PARK.Logging;
using PARK.System.Interfaces.System;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace PARK.Consumer
{
    /// <summary>
    /// 代充值人员名单
    /// </summary>
    [ApiDescriptionSettings(Tag = "Wechat", Name = "TakeEye", Order = 200)]
    [Route("api/wechat/[controller]")]
    public class WechatTakeEyeService : IConsumtakeEyeService, IDynamicApiController, ITransient
    {

        private readonly ISqlSugarRepository<ConsumtakeEyeEntity> _consumtakeEyeRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="WechatTakeEyeService"/>类型的新实例
        /// </summary>
        public WechatTakeEyeService(
            ISqlSugarRepository<ConsumtakeEyeEntity> consumtakeEyeRepository,
            IUserManager userManager)
        {
            _consumtakeEyeRepository = consumtakeEyeRepository;
            _db = _consumtakeEyeRepository.Context;
            _userManager = userManager;
        }

        #region 获取代充人员
        /// <summary>
        /// 获取代充人员
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("GetTakeEyeList")]
        public async Task<dynamic> GetTakeEyeList([FromQuery] TakeEyeListQueryInput input)
        {
            var sidx = input.sidx == null ? "CreateDate" : input.sidx;
            var userInfo = await _userManager.GetUserInfo();
            var _EmployeeId = "0";
            if (userInfo != null && userInfo.UserKind == 1 && !string.IsNullOrEmpty(userInfo.EmployeeId))
            {
                _EmployeeId = userInfo.EmployeeId;
            }
            StringBuilder dbSql = new StringBuilder("select a.Id,a.EmployeeId,a.TakeEyeId,a.TakeEyeJob,a.TakeEyeName,a.TakeEyeCardNo,a.CreateDate,a.CompanyName,b.RechargeBalance from consum_take_eye a inner join base_employee b on a.TakeEyeId=b.EmployeeId");
            dbSql.AppendFormat(" where a.EmployeeId='{0}'", _EmployeeId);            
            var data = await _db.SqlQueryable<ConsumtakeEyeListOutput>(dbSql.ToString()).Select(it => new ConsumtakeEyeListOutput
            {
                Id = it.Id,
                EmployeeId = it.EmployeeId,
                TakeEyeId = it.TakeEyeId,
                TakeEyeJob = it.TakeEyeJob,
                TakeEyeName = it.TakeEyeName,
                TakeEyeCardNo = it.TakeEyeCardNo,
                CreateDate = it.CreateDate,
                CompanyName = it.CompanyName,
                RechargeBalance = it.RechargeBalance
            }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<ConsumtakeEyeListOutput>.SqlSugarPageResult(data);
        }
        #endregion
        
        #region 添加代充人员
        /// <summary>
        /// 添加代充人员
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("AddtakeEye")]
        public async Task AddtakeEye([FromBody] ConsumtakeEyeCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            new Logger().Debug("companyId:"+userInfo.companyId);
            if (userInfo != null && !string.IsNullOrEmpty(input.TakeEyeId))
            {
                //检查是否重复
                var et = _db.Queryable<ConsumtakeEyeEntity>()
                    .Where(d => d.EmployeeId.Equals(userInfo.EmployeeId) && d.TakeEyeId==input.TakeEyeId)
                    .ToList().FirstOrDefault();
                if (et != null)
                {
                    throw PARKException.Oh("已添加所选代充人员！");
                }
                var emp = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == input.TakeEyeId);
                if (emp != null)
                {
                    var entity = input.Adapt<ConsumtakeEyeEntity>();
                    entity.Id = YitIdHelper.NextId().ToString();
                    entity.EmployeeId = userInfo.EmployeeId;
                    entity.TakeEyeId = emp.EmployeeId;
                    entity.TakeEyeJob = emp.JobNum;
                    entity.TakeEyeName = emp.RealName;
                    entity.TakeEyeCardNo = emp.CardNo;
                    entity.CreateDate = DateTime.Now;
                    entity.CreateUser = userInfo.userId;
                    entity.CreateUserName = userInfo.userName;
                    entity.CompanyId = emp.CompanyId;
                    entity.CompanyName = emp.CompanyName;
                    var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                    if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1000);
                }
                else
                {
                    throw PARKException.Bah("所选代充人员不存在!");
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion

        #region 删除代充人员
        /// <summary>
        /// 删除代充人员
        /// </summary>
        /// <returns></returns>
        [HttpPost("DeletetakeEye")]
        public async Task DeletetakeEye([FromBody] ConsumtakeEyeCrDelete input)
        {
            new Logger().Debug("DeletetakeEye->id:" + input.id);
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && !string.IsNullOrEmpty(input.id))
            {
                StringBuilder dbSql = new StringBuilder("delete from consum_take_eye ");
                dbSql.AppendFormat(" where id='{0}'", input.id);
                var Paras = new List<SugarParameter>();
                var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1002);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion
    }
}
